package com.github.lee.unsplash.global.interceptor

import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody

class ResponseInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val response = chain.proceed(chain.request())
        val data = response.body?.string()
        val headers = response.headers
        val pageSize = headers["x-per-page"]?.toInt() ?: 0
        val total = headers["x-total"]?.toInt() ?: 0

        val limit = headers["x-ratelimit-limit"]?.toInt() ?: 0
        val remaining = headers["x-ratelimit-remaining"]?.toInt() ?: 0

        val code = if (remaining <= 0) {
            2000
        } else {
            if (data.isNullOrEmpty()) {
                1000
            } else {
                response.code
            }
        }
        val msg = when (code) {
            200 -> ""
            400 -> "Bad request"
            401 -> "Invalid Access Token"
            403 -> "Missing permissions to perform request"
            404 -> "The requested resource doesn’t exist"
            500, 503 -> "Something went wrong on our end"
            1000 -> "Response data is null"
            2000 -> "The number of requests exceeds the limit"
            else -> "Unknown response code"
        }

        val newResponseJson = when {
            null == data -> {
                ("{\"code\":$code," +
                        "\"msg\":\"$msg\"," +
                        "\"limit\":$limit," +
                        "\"remaining\":$remaining," +
                        "\"data\":null}")
            }
            data.startsWith("{") -> {
                ("{\"code\":$code," +
                        "\"msg\":\"$msg\"," +
                        "\"limit\":$limit," +
                        "\"remaining\":$remaining," +
                        "\"data\":$data}")
            }
            data.startsWith("[") -> {
                ("{\"code\":$code," +
                        "\"msg\":\"$msg\"," +
                        "\"pageSize\":$pageSize," +
                        "\"total\":$total," +
                        "\"limit\":$limit," +
                        "\"remaining\":$remaining," +
                        "\"data\":$data}")
            }
            else -> {
                ("{\"code\":$code," +
                        "\"msg\":\"$msg\"," +
                        "\"pageSize\":$pageSize," +
                        "\"total\":$total," +
                        "\"limit\":$limit," +
                        "\"remaining\":$remaining," +
                        "\"data\":null}")
            }
        }
        return response.newBuilder()
            .code(200)
            .body(newResponseJson.toResponseBody())
            .build()
    }
}